<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="学员姓名" prop="studentName">
        <el-input
          v-model="queryParams.studentName"
          placeholder="请输入学员姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="学号" prop="studentNo">
        <el-input
          v-model="queryParams.studentNo"
          placeholder="请输入学号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="科目" prop="subjectCode">
        <el-select v-model="queryParams.subjectCode" placeholder="请选择科目" clearable>
          <el-option
            v-for="subject in subjectOptions"
            :key="subject.subjectCode"
            :label="subject.subjectName"
            :value="subject.subjectCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="考试结果" prop="result">
        <el-select v-model="queryParams.result" placeholder="请选择考试结果" clearable>
          <el-option label="通过" value="通过" />
          <el-option label="未通过" value="未通过" />
          <el-option label="缺考" value="缺考" />
        </el-select>
      </el-form-item>
      <el-form-item label="考试时间" prop="examTime">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['jiaxiao:exam:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['jiaxiao:exam:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['jiaxiao:exam:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['jiaxiao:exam:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="examList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="学号" align="center" prop="studentNo" />
      <el-table-column label="学员姓名" align="center" prop="studentName" />
      <el-table-column label="科目" align="center" prop="subjectName" />
      <el-table-column label="考试次数" align="center" prop="attemptNo" />
      <el-table-column label="成绩" align="center" prop="score" />
      <el-table-column label="结果" align="center" prop="result">
        <template slot-scope="scope">
          <el-tag :type="getResultTagType(scope.row.result)">
            {{ scope.row.result }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="考试时间" align="center" prop="examTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.examTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['jiaxiao:exam:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['jiaxiao:exam:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 考试记录登记/修改弹窗 -->
    <ExamRecordDialog 
      :visible.sync="dialogVisible" 
      :title="dialogTitle"
      :editingRecord="editingRecord"
      @success="handleDialogSuccess"
    />
  </div>
</template>

<script>
import { listExamRecord, getExamRecord, delExamRecord, addExamRecord, updateExamRecord, registerExamRecord } from "@/api/jiaxiao/exam";
import { listStudent } from "@/api/jiaxiao/student";
import { listSubject } from "@/api/jiaxiao/subject";
import ExamRecordDialog from "./components/ExamRecordDialog.vue";

export default {
  name: "ExamRecord",
  components: {
    ExamRecordDialog
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 学员考试记录表格数据
      examList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 弹窗显示状态
      dialogVisible: false,
      // 弹窗标题
      dialogTitle: "登记考试记录",
      // 编辑中的记录（传给子组件）
      editingRecord: null,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        studentName: null,
        studentNo: null,
        subjectCode: null,
        result: null,
        examTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        studentId: [
          { required: true, message: "学员不能为空", trigger: "change" }
        ],
        subjectId: [
          { required: true, message: "科目不能为空", trigger: "change" }
        ],
        result: [
          { required: true, message: "考试结果不能为空", trigger: "change" }
        ],
        examTime: [
          { required: true, message: "考试时间不能为空", trigger: "change" }
        ]
      },
      // 学员选项
      studentOptions: [],
      // 科目选项
      subjectOptions: []
    };
  },
  created() {
    this.getList();
    this.getStudentOptions();
    this.getSubjectOptions();
  },
  methods: {
    /** 查询学员考试记录列表 */
    getList() {
      this.loading = true;
      listExamRecord(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.examList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 获取学员选项 */
    getStudentOptions() {
      listStudent({}).then(response => {
        this.studentOptions = response.rows;
      });
    },
    /** 获取科目选项 */
    getSubjectOptions() {
      listSubject({}).then(response => {
        this.subjectOptions = response.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        examId: null,
        studentId: null,
        subjectId: null,
        attemptNo: null,
        score: null,
        result: null,
        examTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.examId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.editingRecord = null;
      this.dialogTitle = "登记考试记录";
      this.dialogVisible = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const examId = (row && row.examId) || this.ids;
      if (!examId) return;
      getExamRecord(examId).then(response => {
        this.editingRecord = response.data;
        this.dialogTitle = "修改学员考试记录";
        this.dialogVisible = true;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.examId != null) {
            updateExamRecord(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            // 使用登记接口，包含业务规则
            registerExamRecord(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 弹窗成功回调 */
    handleDialogSuccess() {
      this.getList();
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const examIds = row.examId || this.ids;
      this.$modal.confirm('是否确认删除学员考试记录编号为"' + examIds + '"的数据项？').then(function() {
        return delExamRecord(examIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('jiaxiao/exam/export', {
        ...this.queryParams
      }, `exam_${new Date().getTime()}.xlsx`)
    },
    /** 学员选择变化 */
    handleStudentChange(studentId) {
      // 可以在这里添加根据学员获取科目的逻辑
    },
    /** 科目选择变化 */
    handleSubjectChange(subjectId) {
      // 可以在这里添加根据科目获取相关信息的逻辑
    },
    /** 获取结果标签类型 */
    getResultTagType(result) {
      switch(result) {
        case '通过': return 'success';
        case '未通过': return 'danger';
        case '缺考': return 'warning';
        default: return '';
      }
    }
  }
};
</script>
